import http from "@/api";

export namespace Chat {
  export interface ChatRequest {
    message: string;
    memoryId?: string;
  }

  export interface ChatResponse {
    data: string;
    code: number;
    message: string;
  }

  export interface ChatSession {
    id: string;
    title: string;
    createdAt: Date;
    updatedAt: Date;
    messageCount: number;
  }
}

/**
 * @name AI聊天模块
 */
// 发送聊天消息 - 同步版本
export const sendChatMessage = (params: Chat.ChatRequest) => {
  return http.post<Chat.ChatResponse>(`http://localhost:8081/api/v1/chat/askSync`, params);
};

// 发送聊天消息 - 流式版本 (TEXT_XML_VALUE)
export const sendChatMessageStream = (params: Chat.ChatRequest, onMessage: (chunk: string) => void, onComplete: () => void, onError: (error: any) => void) => {
  // 使用 fetch 实现流式请求，接收 text/xml 格式
  fetch(`http://localhost:8081/api/v1/chat/askStream`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'text/xml',
    },
    body: JSON.stringify(params)
  }).then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const reader = response.body?.getReader();
    const decoder = new TextDecoder();

    function readStream(): Promise<void> {
      return reader!.read().then(({ done, value }) => {
        if (done) {
          onComplete();
          return;
        }

        const chunk = decoder.decode(value, { stream: true });
        // 处理可能的XML格式数据，直接传递文本内容
        onMessage(chunk);

        return readStream();
      });
    }

    return readStream();
  }).catch(error => {
    onError(error);
  });
};

// 会话管理相关API
export const createChatSession = () => {
  return http.post<{ sessionId: string }>(`http://localhost:8081/api/v1/chat/session/create`);
};

export const getChatSessions = () => {
  return http.get<Chat.ChatSession[]>(`http://localhost:8081/api/v1/chat/sessions`);
};

export const deleteChatSession = (sessionId: string) => {
  return http.delete(`http://localhost:8081/api/v1/chat/session/${sessionId}`);
};

export const updateChatSessionTitle = (sessionId: string, title: string) => {
  return http.put(`http://localhost:8081/api/v1/chat/session/${sessionId}/title`, { title });
};